from flask import Flask, render_template, request, redirect, url_for
import requests
# ini文件
import configparser
import os
import random
import json
# 读取配置文件
config = configparser.ConfigParser()
api_count = 0
if os.path.exists('config.ini'):
    config.read('config.ini')
    init = config.get('settings', 'init')
else:
    # 创建配置文件
    config.add_section('settings')
    config.add_section('InAWord')
    config.set('settings', 'init', 'False')
    config.set('InAWord', 'iaw', json.dumps(['付出就会有收获，这收获不一定就是结果，也可以是经过。','真正无穷的自由，会包容你所有的思念']))
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
app = Flask(__name__)

@app.route('/')
def index():
    if init == 'False':
        return render_template('init.html')
    else:
        return render_template('index.html')

@app.route('/init', methods=['POST'])
def init_config():
    # 读取表单数据
    admin_name = request.form.get('admin_name')
    admin_password = request.form.get('admin_password')
    # 写入配置文件
    config.set('settings', 'admin_name', admin_name)
    config.set('settings', 'admin_password', admin_password)
    config.set('settings', 'init', 'True')
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
    return redirect(url_for('index'))
@app.route('/login-submit', methods=['POST'])
def login():
    # 读取表单数据
    username = request.form.get('username')
    password = request.form.get('password')
    # 读取配置文件
    admin_name = config.get('settings', 'admin_name')
    admin_password = config.get('settings', 'admin_password')
    # 验证用户名和密码
    if username == admin_name and password == admin_password:
        return redirect(url_for('manage'))
    else:
        return redirect(url_for('login'))
@app.route('/login')
def login_page():
    return render_template('login.html')
@app.route('/manage')
def manage():
    return render_template('manage.html', api_count=api_count)
@app.route('/get')
def get():
    # 读取配置文件
    global api_count
    api_count += 1
    config = configparser.ConfigParser()
    config.read('config.ini')
    iaw = json.loads(config.get('InAWord', 'iaw'))
    return iaw[random.randint(0,len(iaw)-1)]
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)